#!/usr/bin/env perl

use strict;
use warnings;

my $PORT = "/dev/tty.usbserial";

print "setting stty on $PORT\n";
#system("stty -f $PORT 19200 raw -parenb -parodd cs8 -hupcl -cstopb clocal");
system("stty -f $PORT 19200 raw -parenb -parodd cs8 -hupcl -cstopb clocal");

print "opening port $PORT\n";
my $portfh;
open(FH,"+<$PORT") || die "opening $PORT for input: $!";


    
#
# send some characters.
sub sendMsg {
    my ($portfh, $msg) = @_;
    syswrite $portfh, $msg, length($msg);
}

# get some chars
sub getMsg {
    my ($portfh) = @_;
    my ($inbuff,$ch,$rin,$rout) = ('','','','');
    # Read it back.  This reads stuff until there is no character
    # for 0.3 seconds in a row.  If this knew the reply length,
    # it could do something smarter.  As it is, sometime .3 seconds
    # isn't long enough.
    vec($rin,fileno("portfh"),1) = 1;
    while ( select($rout=$rin, undef,undef, 0.3) ) {
        $ch = '';
        sysread("portfh",$ch,1);
        $inbuff .= $ch;
    }
    return $inbuff;
}

my $str;

print "sending message\n";
sendMsg( $portfh, "re364\x02\x01\x04" );
print "waiting for response...\n";
$str = getMsg( $portfh );
print "str: $str\n";
sendMsg( $portfh, "acknwlge");
$str = getMsg( $portfh );
print "str: $str\n";
$str = getMsg( $portfh );
print "str: $str\n";

